package com.xuzm.netty.test;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.function.Function;

public class ClientCustomChannelHandler extends ChannelInboundHandlerAdapter {
    private Function<ChannelHandlerContext, String> msgFunction;

    public ClientCustomChannelHandler(Function<ChannelHandlerContext, String> msgFunction) {
        this.msgFunction = msgFunction;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("Client connected to server");

//        // 构造要发送的消息
//        String message = msgFunction.apply(ctx);
//        ByteBuf buf = Unpooled.copiedBuffer(message.getBytes());

        // 发送消息
        String message;
//        while ((message = msgFunction.apply(ctx)) != null) {
//            Thread.sleep(500);
//            System.out.println(message);
////            ByteBuf buf = Unpooled.copiedBuffer(message.getBytes());
////            ctx.writeAndFlush(buf);
//        }

//        ctx.close();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 处理接收到的消息
        System.out.println("Received message from server: " + msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 处理异常
        cause.printStackTrace();
        ctx.close();
    }
}
